/**
 * 项目数据库初始化脚本
 * 创建项目相关集合与索引
 */

// 云开发初始化
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

// 引入集合架构定义
const { 
  PROJECT_SCHEMA, 
  PROJECT_BRANCH_SCHEMA, 
  PROJECT_STATE_HISTORY_SCHEMA 
} = require('./cloud_db_schema');

// 主函数：初始化数据库
async function initDatabase() {
  try {
    console.log('开始初始化数据库...');
    
    // 创建集合和索引
    await createProjectsCollection();
    await createProjectBranchesCollection();
    await createProjectStateHistoryCollection();
    
    console.log('数据库初始化完成!');
    return { code: 0, message: '数据库初始化成功' };
  } catch (error) {
    console.error('数据库初始化失败:', error);
    return { code: -1, message: '数据库初始化失败: ' + error.message };
  }
}

// 创建项目集合
async function createProjectsCollection() {
  try {
    // 检查集合是否已存在
    const collections = await db.listCollections().get();
    const exists = collections.data.some(collection => collection.name === 'projects');
    
    if (!exists) {
      // 创建集合
      await db.createCollection('projects', PROJECT_SCHEMA);
      console.log('创建"projects"集合成功');
    } else {
      console.log('"projects"集合已存在');
      
      // 如果需要更新架构，可以使用updateCollection命令
      // 注意：微信云开发不直接支持updateCollection，需要根据实际情况调整
      // await db.runCommand({ collMod: 'projects', validator: PROJECT_SCHEMA.validator });
    }
    
    // 创建索引
    await db.collection('projects').createIndexes([
      {
        key: { model: 1 },
        name: 'model_index'
      },
      {
        key: { projectType: 1 },
        name: 'projectType_index'
      },
      {
        key: { startDate: 1 },
        name: 'startDate_index'
      },
      {
        key: { deadline: 1 },
        name: 'deadline_index'
      },
      {
        key: { masterBranchId: 1 },
        name: 'masterBranch_index'
      }
    ]);
    
    console.log('项目集合索引创建成功');
  } catch (error) {
    console.error('创建项目集合失败:', error);
    throw error;
  }
}

// 创建项目分支集合
async function createProjectBranchesCollection() {
  try {
    // 检查集合是否已存在
    const collections = await db.listCollections().get();
    const exists = collections.data.some(collection => collection.name === 'project_branches');
    
    if (!exists) {
      // 创建集合
      await db.createCollection('project_branches', PROJECT_BRANCH_SCHEMA);
      console.log('创建"project_branches"集合成功');
    } else {
      console.log('"project_branches"集合已存在');
      
      // 如果需要更新架构，可以使用updateCollection命令
      // 注意：微信云开发不直接支持updateCollection，需要根据实际情况调整
      // await db.runCommand({ collMod: 'project_branches', validator: PROJECT_BRANCH_SCHEMA.validator });
    }
    
    // 创建索引
    await db.collection('project_branches').createIndexes([
      {
        key: { projectId: 1 },
        name: 'projectId_index'
      },
      {
        key: { parentId: 1 },
        name: 'parentId_index'
      },
      {
        key: { projectId: 1, isMaster: 1 },
        name: 'masterBranch_index'
      },
      {
        key: { projectId: 1, isActive: 1 },
        name: 'activeBranch_index'
      },
      {
        key: { createdTime: -1 },
        name: 'createdTime_index'
      }
    ]);
    
    console.log('项目分支集合索引创建成功');
  } catch (error) {
    console.error('创建项目分支集合失败:', error);
    throw error;
  }
}

// 创建项目状态历史集合
async function createProjectStateHistoryCollection() {
  try {
    // 检查集合是否已存在
    const collections = await db.listCollections().get();
    const exists = collections.data.some(collection => collection.name === 'project_state_history');
    
    if (!exists) {
      // 创建集合
      await db.createCollection('project_state_history', PROJECT_STATE_HISTORY_SCHEMA);
      console.log('创建"project_state_history"集合成功');
    } else {
      console.log('"project_state_history"集合已存在');
      
      // 如果需要更新架构，可以使用updateCollection命令
      // 注意：微信云开发不直接支持updateCollection，需要根据实际情况调整
      // await db.runCommand({ collMod: 'project_state_history', validator: PROJECT_STATE_HISTORY_SCHEMA.validator });
    }
    
    // 创建索引
    await db.collection('project_state_history').createIndexes([
      {
        key: { projectId: 1, branchId: 1, createdTime: -1 },
        name: 'project_branch_time_index'
      },
      {
        key: { branchId: 1 },
        name: 'branchId_index'
      },
      {
        key: { createdBy: 1 },
        name: 'createdBy_index'
      },
      {
        key: { eventType: 1 },
        name: 'eventType_index'
      }
    ]);
    
    console.log('项目状态历史集合索引创建成功');
  } catch (error) {
    console.error('创建项目状态历史集合失败:', error);
    throw error;
  }
}

// 导出初始化函数
module.exports = {
  initDatabase
};

// 如果直接运行此脚本，则执行初始化
if (require.main === module) {
  initDatabase().then(result => {
    console.log(result);
    process.exit(result.code === 0 ? 0 : 1);
  });
} 